package com.vb.webpress.servlets;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

/**
 * Servlet implementation class for Servlet: UploadServlet
 *
 */
 public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public UploadServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.getWriter().println("Please upload via POST");
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("test");
		File file = null;
		DiskFileUpload diskFileUpload = new DiskFileUpload();
		String url = null;
		String id = request.getParameter("hidden_frame");
		
		try{
			List<FileItem> list = diskFileUpload.parseRequest(request);
				
			for(FileItem fileItem : list){
					if("file".equals(fileItem.getFieldName())){
						File remoteFile = new File(new String(fileItem.getName().getBytes(), "UTF-8"));
						
						file = new File(this.getServletContext().getRealPath("image") + System.currentTimeMillis(), remoteFile.getName());
						file.getParentFile().mkdirs();
						file.createNewFile();
						url = file.getAbsolutePath();
						
						InputStream ins = fileItem.getInputStream();
						OutputStream ous = fileItem.getOutputStream();
						response.getWriter().println("<script type=\"text/javascript\">parent.callback("+ id +", " + url + ")</script>");
						try{
							byte[] buffer = new byte[1024];
							int len = 0;
							while((len = ins.read(buffer)) > -1){
								ous.write(buffer, 0, len);
							}
							
						}finally{
							ous.close();
							ins.close();
						}
					}
				}
		}catch(Exception e){
			
		}
	}   	  	    
}